package com.wr;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            } },"A").start();
        new Thread(()->{for (int i = 0; i < 40; i++) {
            ticket.sale();
        }},"B").start();
        new Thread(()->{for (int i = 0; i < 40; i++) {
            ticket.sale();
        }},"C").start();
    }
}


// oop 资源类
class Ticket{

    private int number = 30;

    Lock lock = new ReentrantLock();

    public void sale(){
        // 加锁
        lock.lock();

        try {
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+number--+"张票，剩余："+number+"张票。");
            }
        } finally {
            lock.unlock();   // 解锁
        }
    }
}